﻿
using UnityEngine;
using System.Collections;
using System.IO;
using System.Collections.Generic;
using LitJson;



/*=============================
 *创建者：LR
 *日  期：2015.8.4
 *加载资源
 *============================= 
 * */
public class LoadAssets : IUserInterface
{
    public static string fileName = "12.zip";
    private string bundleType = ".assetbundle";
    public readonly string filepath = "ftp://192.168.1.107:2121/" + fileName;
    // string url = "ftp://192.168.1.103:30/";

    public static readonly string PathURL =
#if UNITY_ANDROID
		"jar:file://" + Application.dataPath + "!/assets/";
#elif UNITY_IPHONE
		Application.dataPath + "/Raw/";
#elif UNITY_STANDALONE_WIN || UNITY_EDITOR
 Application.dataPath + "/StreamingAssets/";
#else
        string.Empty;
#endif

    void Start()
    {
        CreateFile(Application.persistentDataPath, "lr.txt", System.DateTime.Now.ToString());

    }
    void OnGUI()
    {
  
        if (GUILayout.Button("URL assetbundle"))
        {
            StartCoroutine(LoadAssetsFromSever(filepath, 1));
        }
        if (GUILayout.Button("下载到本地"))
        {
            StartCoroutine(DownLoadAssetsFromSeverToLocal(filepath, fileName));
        }
        if (GUILayout.Button("读取下载文件"))
        {
            StartCoroutine(LoadAssetsFromLocal("file:///" + Application.persistentDataPath, "7", bundleType));
        }
        if (GUILayout.Button("删除文件"))
        {
            DeleteFile("file:///" + Application.persistentDataPath, "7.jpg");
        }
        if (GUILayout.Button("打开场景"))
        {
            //StartCoroutine(LoadScene());
            StartCoroutine(LoadScene("Game.unity3d", "Example X - Character"));
        }
        if (GUILayout.Button("打开压缩文件"))
        {

            StartCoroutine(LoadMainObject(Application.persistentDataPath + "/sod.bat",true));
         
        }
    }

    public IEnumerator LoadScene(string fileName, string sceneName)
    {
        Caching.CleanCache();
        Debug.Log(Application.persistentDataPath);
        WWW download = new WWW("file:///" + Application.persistentDataPath + "/" + fileName);
        yield return download;
        var bundle = download.assetBundle;
        Application.LoadLevel(sceneName);
    }
    public IEnumerator LoadMainObject(string path, bool encryption)
    {

        if (System.IO.File.Exists(path))
        {
            FileStream assetIO = new FileStream(path, FileMode.Open, FileAccess.Read);
            byte[] assetBytes = encryption == true ? new byte[assetIO.Length - 3] : new byte[assetIO.Length];
            int length = encryption == true ? (int)assetIO.Length - 3 : (int)assetIO.Length;
            assetIO.Read(assetBytes, 0, length);
            assetIO.Close();
            assetIO.Dispose();
            AssetBundleCreateRequest assetRequest = AssetBundle.CreateFromMemory(assetBytes);
            yield return assetRequest;

            if (assetRequest.assetBundle)
            {
                UnityEngine.Object[] assetArry = assetRequest.assetBundle.LoadAll();
                foreach (UnityEngine.Object item in assetArry)
                {
                    if (item.GetType().ToString() == "UnityEngine.Texture2D")
                    {
                        GetName("pict").GetComponent<UITexture>().mainTexture = assetRequest.assetBundle.Load("7") as Texture;
                        GetName("pict").GetComponent<UITexture>().MakePixelPerfect();
                    }
                    //Instantiate(item);
                }
                AssetBundle bundle = assetRequest.assetBundle;
                Debug.Log(bundle.name);
                bundle.Unload(false);
            }
            Resources.UnloadUnusedAssets();
            System.GC.Collect();
        }

    }
    public IEnumerator LoadAssetsFromJsonConfig()
    {
#if UNITY_EDITOR
        string filepath = Application.dataPath + "/StreamingAssets" + "/json.txt";
#elif UNITY_IPHONE
	  string filepath = Application.dataPath +"/Raw"+"/json.txt";
#endif

        StreamReader sr = File.OpenText(filepath);
        string strLine = sr.ReadToEnd();
        JsonData jd = JsonMapper.ToObject(strLine);
        JsonData gameObjectArray = jd["GameObjects"];
        int i, j, k;
        for (i = 0; i < gameObjectArray.Count; i++)
        {
            JsonData senseArray = gameObjectArray[i]["scenes"];
            for (j = 0; j < senseArray.Count; j++)
            {
                string sceneName = (string)senseArray[j]["name"];
                if (!sceneName.Equals("Assets/NGUI/Examples/Scenes/Example 11 - Drag & Drop.unity"))
                {
                    continue;
                }
                JsonData gameObjects = senseArray[j]["gameObject"];

                for (k = 0; k < gameObjects.Count; k++)
                {
                    string objectName = (string)gameObjects[k]["name"];
                    //	string asset = "Prefab/" + objectName;


                    string asset = "file:///" + Application.persistentDataPath + "/JsonBundle/" + objectName + ".assetbundle";
                    //if (!File.Exists(asset))
                    //{
                    //    WWW sever = new WWW("");
                    //}
                    Vector3 pos = Vector3.zero;
                    Vector3 rot = Vector3.zero;
                    Vector3 sca = Vector3.zero;


                    JsonData position = gameObjects[k]["position"];
                    JsonData rotation = gameObjects[k]["rotation"];
                    JsonData scale = gameObjects[k]["scale"];

                    pos.x = float.Parse((string)position[0]["x"]);
                    pos.y = float.Parse((string)position[0]["y"]);
                    pos.z = float.Parse((string)position[0]["z"]);

                    rot.x = float.Parse((string)rotation[0]["x"]);
                    rot.y = float.Parse((string)rotation[0]["y"]);
                    rot.z = float.Parse((string)rotation[0]["z"]);

                    sca.x = float.Parse((string)scale[0]["x"]);
                    sca.y = float.Parse((string)scale[0]["y"]);
                    sca.z = float.Parse((string)scale[0]["z"]);

                    WWW www = new WWW(asset);
                    yield return www;
                    if (www.isDone)
                    {
                        if (www.error != null)
                        {

                            Debug.Log(www.error);
                        }
                        //  GameObject ob = (GameObject)Instantiate((www.assetBundle.mainAsset), pos, Quaternion.Euler(rot));
                        //   ob.transform.localScale = sca;
                    }
                }
            }
        }
    }
    IEnumerator LoadAssetsFromLocal(string path, string fileName, string bundleType)
    {
        WWW www = new WWW( path + "/" + fileName + bundleType);
        yield return www;
        if (www.isDone)
        {
            // print(www.assetBundle.name);

            if (www.error != null)
            {
                print(www.error);
            }

            Object[] asstArry = www.assetBundle.LoadAll();
            foreach (Object item in asstArry)
            {
                if (item.GetType().ToString() == "UnityEngine.Texture2D")
                {
                    GetName("pict").GetComponent<UITexture>().mainTexture = www.assetBundle.mainAsset as Texture2D;
                }
                if (item.GetType().ToString() == "UnityEngine.MovieTexture")
                {

                }

            }
            // Application.LoadLevel("Example X - Character");
            //GameObject obj = Instantiate(www.assetBundle.Load(fileName)) as GameObject;
            // obj.transform.parent = GetName("GameObject").transform;
        }
        www.assetBundle.Unload(false);
        Resources.UnloadUnusedAssets();

    }

  
    /// <summary>
    /// 从服务器上加载到内存
    /// </summary>
    /// <param name="dataPath"></param>
    /// <param name="version"></param>
    /// <returns></returns>
    private IEnumerator LoadAssetsFromSever(string dataPath, int version)
    {
        WWW www = WWW.LoadFromCacheOrDownload(filepath, version);
        yield return www;

        if (www.isDone)
        {

            AssetBundle bundle = www.assetBundle;

            if (www.error != null)
            {
                print("error");
            }
            else
      
            {
                print("www" + bundle.mainAsset.name);
                //   GetName("GameObject").GetComponent<UITexture>().mainTexture = bundle.mainAsset as Texture;
            }
            bundle.Unload(false);

        }

        Resources.UnloadUnusedAssets();
        System.GC.Collect();
    }

    /// <summary>
    /// 服务器上下载资源并创建到本地
    /// </summary>
    /// <param name="url"></param>
    /// <param name="fileName"></param>
    /// <returns></returns>
    IEnumerator DownLoadAssetsFromSeverToLocal(string url, string fileName)
    {
        WWW www = new WWW(url);

        yield return www;
        if (www.error != null)
        {
            print(www.error);
        }
        else
        {
            if (www.isDone)
            {
                byte[] assetBytes = www.bytes;
                int length = assetBytes.Length;
                CreateModelFile(Application.persistentDataPath, fileName, assetBytes, length);
            }
        }

    }

    void CreateModelFile(string path, string fileName, byte[] info, int length)
    {
        Stream sm;
        FileInfo fi = new FileInfo(path + "//" + fileName);
        if (!fi.Exists)
        {
            sm = fi.Create();
        }
        else
        {
            print("Assets had existed");
            return;
        }
        sm.Write(info, 0, length);
        sm.Close();
        sm.Dispose();
        print("下载完毕！");
    }

    /// <summary>
    /// 用于创建文本
    /// </summary>
    /// <param name="path"></param>
    /// <param name="fileName"></param>
    /// <param name="info">文本</param>
    void CreateFile(string path, string fileName, string info)
    {
        StreamWriter sw;
        FileInfo fi = new FileInfo(path + "//" + fileName);
        if (!fi.Exists)
        {
            sw = fi.CreateText();

        }
        else
        {
            sw = fi.AppendText();
        }
        sw.WriteLine(info);
        sw.Close();
        sw.Dispose();
    }
    ArrayList LoadFile(string path, string fileName)
    {
        StreamReader sr = null;
        try
        {
            sr = File.OpenText(path + "//" + fileName);
        }
        catch (System.Exception e)
        {

            throw e;
            //return null;
        }
        string line;
        ArrayList arrlist = new ArrayList();
        while ((line = sr.ReadLine()) != null)
        {
            arrlist.Add(line);
        }
        sr.Close();
        sr.Dispose();
        return arrlist;
    }
    void DeleteFile(string path, string fileName)
    {
        File.Delete(path + "//" + fileName);
    }
    void DeleteFileFromBundle(string path, string fileName)
    {
        File.Delete(PathURL + "/" + fileName);
    }

}